package com.wang.gallerybackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.wang.gallerybackend.exception.BusinessException;
import com.wang.gallerybackend.exception.ErrorCode;
import com.wang.gallerybackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * url图片上传
 */
@Service
public class UrlPictureUploadImpl extends PictureUpload {
	@Override
	protected void processFile(Object inputSource, File file) throws IOException {
		String fileUrl = (String) inputSource;
		HttpUtil.downloadFile(fileUrl, file);
	}

	@Override
	protected String getOriginalFilename(Object inputSource) {
		String fileUrl = (String) inputSource;
		return FileUtil.mainName(fileUrl);
	}

	@Override
	protected void validPicture(Object inputSource) {
		String fileUrl = (String) inputSource;
		//校验非空
		ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
		//校验url格式
		try {
			URL url = new URL(fileUrl);
		} catch (Exception e) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式错误");
		}
		//校验URL的协议
		ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://")
				, ErrorCode.PARAMS_ERROR, "仅支持http和https协议的文件地址");
		//发送HEAD请求验证文件是否存在
		HttpResponse execute = null;
		try {
			execute = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
			if (execute.getStatus() != HttpStatus.HTTP_OK) {
				return;
			}

			//文件存在，文件类型校验
			String contentType = execute.header("Content-Type");
			if (StrUtil.isNotBlank(contentType)) {
				//允许的图片类型
				List<String> allowFileType = List.of("image/jpeg", "image/png", "image/gif", "image/webp");
				System.out.println("上传文件的 Content-Type: " + contentType);
				ThrowUtils.throwIf(!allowFileType.contains(contentType), ErrorCode.PARAMS_ERROR, "文件类型错误");
			}
			//文件大小校验
			long contentLength = Long.parseLong(execute.header("Content-Length"));
			try {
				ThrowUtils.throwIf(contentLength > MAXSIZE, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
			} catch (NumberFormatException e) {
				ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "文件大小格式异常");
			}
		} finally {
			if (execute != null) {
				execute.close();
			}
		}
	}
}
